﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SnippetBox.Core.Common.Extensions;
using SnippetBox.Core.Common.Text;
using SnippetBox.Core.Common.XSS;
using SnippetBox.Core.Data.Models;
using SnippetBox.Core.Data.Service;
using SnippetBox.Core.Infrastructure;
using SnippetBox.Web.Models;

namespace SnippetBox.Web.Controllers {
    public class SnippetController : Controller {
        readonly SnippetService _snippetService = new SnippetService();

        public ActionResult Index() {
            var model = new SnippetIndexModel();
            model.LatestSnippets = _snippetService.GetLatestSnippets(count: 10);
            model.PopularSnippets = _snippetService.GetPopularSnippets(count: 10);
            
            return View(model);
        }
        public ActionResult Details(int snippetId) {
            var snippet = _snippetService.GetByIdForDetails(snippetId);

            if (snippet == null)
                return View("NotFound", new NotFoundModel());

            snippet.Views++;
            _snippetService.Save();

            var model = new SnippetDetailsModel(snippet);

            ViewBag.Title = snippet.Title;

            return View(model);
        }

        [Authorize]
        public ActionResult ToggleFavorite(int id) {
            var userService = new UserService();

            var snippet = _snippetService.GetById(id);
            var user = userService.GetByUsername(User.Identity.Name);
            var favorite = user.Favorites.SingleOrDefault(s => s.Snippet.SnippetId == snippet.SnippetId);

            if (favorite != null) {
                snippet.Favorited--;
                user.Favorites.Remove(favorite);
            }
            else {
                snippet.Favorited++;
                user.Favorites.Add(new Favorite {
                    DateCreated = DateTime.Now,
                    Snippet = snippet,
                    User = user
                });                
            }
            
            userService.Save();

            if (Request.IsAjaxRequest())
                return Json(new {success = true });

            return Redirect(snippet.Link);

        }
    }
}
